package com.by.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

/**
 * description:
 * author:zcx
 * lenovo
 * 时间：2022.06.09.20.02
 */
public class TokenFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre"; //请求前过滤
    }

    @Override
    public int filterOrder() {
        return 0; //过滤器执行顺序
    }

    @Override
    public boolean shouldFilter() {
        return true; //是否执行该过滤器
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext=RequestContext.getCurrentContext();//获取当前请求的环境
        HttpServletRequest request=requestContext.getRequest();
        String token=request.getHeader("x-token");
        if(null==token){
            //说明无权访问
            requestContext.setSendZuulResponse(false);//停止向服务发送请求
            //设置网关响应客户端的内容
            requestContext.getResponse().setContentType("application/json;charset=utf-8");
            requestContext.setResponseBody("{code:0,msg:'无权访问'}");
        }
        requestContext.set("token",token);
        return null;
    }
}
